import 'package:flutter/material.dart';
import 'package:flutter_demo1/core/hi_state.dart';
import 'package:flutter_demo1/http/core/hi_error.dart';
import 'package:flutter_demo1/http/dao/home_dao.dart';
import 'package:flutter_demo1/model/home_mo.dart';
import 'package:flutter_demo1/navigator/hi_navigator.dart';
import 'package:flutter_demo1/page/home_tab_page.dart';
import 'package:flutter_demo1/util/color.dart';
import 'package:flutter_demo1/widget/navigation_top_bar.dart';

class HomePage extends StatefulWidget {
  final ValueChanged<int>? onJumpTo;

  const HomePage({super.key, this.onJumpTo});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends HiState<HomePage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  late RouteChangeListener listener;
  late TabController _tabController;
  List<CategoryMo> categoryList = [];
  List<BannerMo> bannerList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: categoryList.length, vsync: this);
    HiNavigator.getInstance().addListener(
      listener = (current, pre) {
        print("homePage:current:::${current.page}");
        print("homePage:pre:::${pre?.page}");
        if (widget == current.page || current.page is HomePage) {
          print("打开了homePage:onResume");
        } else if (widget == pre?.page || pre?.page is HomePage) {
          print("关闭了homePage:onPause");
        }
      },
    );
    loadData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    HiNavigator.getInstance().removeListener(listener);
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Column(
        children: [
          NavigationTopBar(
            _appBar(),
            height: 50,
            color: Colors.white,
            statusStyle: StatusStyle.DARK_CONTENT,
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 60),
            child: _tobBar(),
          ),
          Flexible(
            child: TabBarView(
              controller: _tabController,
              children: categoryList.map((tab) {
                return HomeTabPage(
                  tab.name,
                  //如果是推荐页面,就把广告数据加进去
                  bannerList: tab.name == "推荐" ? bannerList : null,
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }

  //页面实现 AutomaticKeepAliveClientMixin 接口后,设置为true,在PageControl中使用的page,切换的以后就不会被销毁重建了
  @override
  bool get wantKeepAlive => true;

  Widget _tobBar() {
    return TabBar(
      controller: _tabController,
      isScrollable: true,
      labelColor: Colors.black,
      indicator: UnderlineTabIndicator(
        borderSide: BorderSide(color: primary, width: 3),
        //内边距
        insets: EdgeInsets.only(left: 5, right: 5),
      ),
      tabs: categoryList.map<Tab>((tab) {
        return Tab(
          child: Padding(
            padding: EdgeInsets.only(left: 5, right: 5),
            child: Text(tab.name),
          ),
        );
      }).toList(),
    );
  }

  void loadData() async {
    try {
      HomeMo result = await HomeDao.get("推荐");
      if (result.categoryList != null) {
        //最开始初始化的tabController长度是0,所以
        _tabController = TabController(
          length: result.categoryList!.length,
          vsync: this,
        );
      }
      setState(() {
        categoryList = result.categoryList!;
        bannerList = result.bannerList!;
      });
    } on NeedAuth catch (e) {
      print("NeedAuth:${e}");
    } catch (e) {
      print("catch:${e}");
    }
  }

  Widget _appBar() {
    return Padding(
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              if (widget.onJumpTo != null) {
                widget.onJumpTo!(3);
              }
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(23),
              child: Image(
                image: AssetImage('images/avatar.png'),
                height: 46,
                width: 46,
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 15, right: 15),
              child: Container(
                padding: EdgeInsets.only(left: 10),
                height: 32,
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Icon(Icons.search, color: Colors.grey),
              ),
            ),
          ),
          Icon(Icons.explore_outlined, color: Colors.grey),
          Padding(
            padding: EdgeInsets.only(left: 15),
            child: Icon(Icons.mail_outline, color: Colors.grey),
          ),
        ],
      ),
    );
  }
}
